<script lang="ts" setup>
  import { ref, onMounted, onUnmounted, watch } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data: { type: Array as () => Array<Array<number>>, required: true },
    datax: { type: Object as () => any, required: true },
    title: { type: String, default: '' },
    dataName: { type: Object as () => any, default: [] },
    max: { type: Number, default: 250000 },
    min: { type: Number, default: 0 },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  // 动态构建option
  const buildOption = () => {
    return {
      title: {
        text: props.title,
        left: 'center',
        top: '3%',
        textStyle: {
          fontSize: 14,
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'axis',
        appendToBody: true,
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: {
        data: props.dataName,
        top: props.title == '' ? '0%' : '12%',
        itemWidth: 15,
        itemHeight: 10,
        textStyle: {
          fontSize: 12,
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '30%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: props.datax,
        axisTick: {
          alignWithLabel: true,
        },
      },
      yAxis: {
        type: 'value',
        min: props.min,
        max: props.max,
        splitLine: { show: true },
        boundaryGap: [0, '20%'],
      },
      series: (props.dataName || []).map((name: string, idx: number) => ({
        name,
        type: 'bar',
        stack: 'total',
        data: props.data[idx] ?? [],
      })),
    };
  };

  const initCharts = () => {
    if (chartRef.value && !chartInstance) {
      chartInstance = echarts.init(chartRef.value);
      chartInstance.setOption(buildOption(), true);
    }
  };
  const updateChart = () => {
    if (chartRef.value && chartInstance) {
      chartInstance.setOption(buildOption(), true);
    }
  };

  onMounted(() => {
    setTimeout(() => {
      initCharts();
    }, 100);
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.data, props.dataName, props.max, props.min, props.title],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
